<template>
  <el-dialog title="商户信息" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
    <div v-if="fromData.appId == null">加载中...</div>
    <div v-else>
      <el-form :key="newTime" ref="main-form" label-width="150px" :rules="rules" :model="fromData" :inline="true">
        <el-row>
          <el-form-item label="商户号" size="mini">
            <el-input :value="fromData.mchNo" v-model="fromData.mchNo" disabled></el-input>
          </el-form-item>
          <el-form-item label="商户名称" prop="mchName" size="mini">
            <el-input v-model="fromData.mchName" :value="fromData.mchName"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="appId" prop="appId" size="mini">
            <el-input ref="appId" :value="fromData.appId" v-model="fromData.appId"></el-input>
            <el-link type="primary" @click="copyData('appId', fromData.appId)">复制</el-link>
          </el-form-item>
          <el-form-item label="appSecret" prop="appSecret" size="mini">
            <el-input ref="appSecret" :value="fromData.appSecret" v-model="fromData.appSecret"></el-input>
            <el-link type="primary" @click="copyData('appSecret', fromData.appSecret)">复制</el-link>
          </el-form-item>
        </el-row>

        <el-form-item label="标签" size="mini" prop="">
          <el-select v-model="fromData.mchTagId" filterable size="small" multiple clearable>
            <el-option v-for="item in mchTagIdOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关联销售" size="mini" prop="">
          <el-select v-model="fromData.salesId" filterable size="small" clearable>
            <el-option v-for="item in salesIdOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="api开放状态" size="mini" prop="apiStatus">
          <el-select v-model="fromData.apiStatus" filterable size="small" clearable>
            <el-option v-for="item in apiStatusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册状态" size="mini" prop="regStatus">
          <el-select v-model="fromData.regStatus" filterable disabled size="small" clearable>
            <el-option v-for="item in regStatusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登录状态" size="mini" prop="loginStatus">
          <el-select v-model="fromData.loginStatus" filterable size="small" clearable>
            <el-option v-for="item in loginStatusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <h3>商户配置</h3>
        <el-form-item v-for="(item, index) in payOptionList" :key="index" :label="item.label + '通道合集'" size="mini" :prop="item.const">
          <el-select v-model="fromData[item.const]" filterable size="small" clearable>
            <el-option v-for="ite in item.option" :key="ite.value" :label="ite.label" :value="ite.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="交易汇率（单选）" size="mini" prop="settleExchangeRateId">
          <el-select v-model="fromData.settleExchangeRateId" size="small" filterable clearable>
            <el-option v-for="item in settleExchangeRateIdOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="结算费率（单选）" size="mini" prop="settleRateId">
          <el-select v-model="fromData.settleRateId" size="small" filterable clearable>
            <el-option v-for="item in settleRateIdOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="风控集合（单选） " v-if="fromData.CREDIT" size="mini" prop="riskId">
          <el-select v-model="fromData.riskId" size="small" filterable clearable>
            <el-option v-for="item in riskIdOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商户对平台结算币种（单选）" size="mini" prop="settleCurrency">
          <el-select v-model="fromData.settleCurrency" size="small" filterable clearable>
            <el-option v-for="item in currencyOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-form-item label="交易币种(可多选)" size="mini">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0"></div>
            <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="item in currencyOptions" :label="item.value" :value="item.value" :key="item.value">{{ item.label }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <div slot="footer" class="dialog-footer" style=" justify-content: space-between;
  display: flex;">
      <span>
        <el-button type="danger" @click="submitChangeGoogleCode" size="small">重置商户超级管理员的google密钥</el-button>
        <el-button type="danger" @click="changePasswordVisible =true" size="small">重置商户超级管理员的密码</el-button>
      </span>
      <span>
        <el-button @click="close" size="small">取 消</el-button>
        <el-button type="primary" @click="submit" size="small">提 交</el-button>
      </span>
    </div>

    <!-- 修改密码 -->

    <!-- 修改密码 -->
    <el-dialog title="修改密码" :visible.sync="changePasswordVisible" append-to-body :close-on-click-modal="false" width="400px">

      <el-form ref="form-change-password" size="mini" :model="formChangePassword" :rules="rulesChangePassword" label-width="80px" inline>
        <!-- 新密码 -->
        <el-form-item label="密码" prop="password">
          <el-input placeholder="" type="password" v-model="formChangePassword.password" @keyup.enter.native="submitFormChangePassword" clearable></el-input>
        </el-form-item>
        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="password_confirmation">
          <el-input placeholder="" type="password" v-model="formChangePassword.password_confirmation" @keyup.enter.native="submitFormChangePassword" clearable></el-input>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="changePasswordVisible = false" size="mini">取 消</el-button>
        <el-button @click="submitFormChangePassword" size="mini" type="primary">提 交</el-button>
      </div>

    </el-dialog>

  </el-dialog>
</template>

<script>
import ApiMain from '@/api/mch.info';
import productApi from '@/api/product.info';
import rateSettleApi from '@/api/mch.rateSettle';
import rateGroupApi from '@/api/exchangeRate.rateGroup';
import channelApi from '@/api/bank.channel';
import mchTagApi from '@/api/platform.mchTag';
import memberApi from '@/api/system.member';
import collectionApi from '@/api/risk.collection';
import ApiRateBoc from '@/api/exchangeRate.rateBoc';
// product.info mch.rateSettle exchangeRate.rateGroup bank.channel platform.mchTag system.member risk.collection
export default {
  mixins: [
  ],
  props: [
  ],

  data() {
    return {
      changePasswordVisible: false,
      formChangePassword: {
        password: '',
        password_confirmation: '',
      },
      rulesChangePassword: {
        password: [
          { required: true, message: '请输入当前密码', trigger: 'blur' },
        ],

        password_confirmation: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
      },
      newTime: new Date().getTime(),
      rules: {
        settleExchangeRateId: [
          { required: true, message: '请选择交易汇率', trigger: 'blur' },
        ],

        mchName: [
          { required: true, message: '请输入商户名称', trigger: 'blur' },
        ],
        appId: [
          { required: true, message: '请输入appid', trigger: 'blur' },
        ],

        appSecret: [
          { required: true, message: '请输入appSecret', trigger: 'blur' },
        ],

        mchTagId: [
          { required: true, message: '请选择标签', trigger: 'blur' },
        ],

        salesId: [
          { required: true, message: '请选择关联销售', trigger: 'blur' },
        ],

        apiStatus: [
          { required: true, message: '请选择开放状态', trigger: 'blur' },
        ],

        regStatus: [
          { required: true, message: '请选择注册状态', trigger: 'blur' },
        ],

        loginStatus: [
          { required: true, message: '请选择登录状态', trigger: 'blur' },
        ],

        settleRateId: [
          { required: true, message: '请选择结算汇率', trigger: 'blur' },
        ],

        riskId: [
          { required: true, message: '请选择风控集合', trigger: 'blur' },
        ],

        settleCurrency: [
          { required: true, message: '请选择对商户结算币种', trigger: 'blur' },
        ],
      },
      onland: false,
      checkAll: false,
      checkedCities: [],

      isIndeterminate: true,
      dialogVisible: false,
      payOptionList: [],
      currencyOptions: [],
      settleCurrencyOptions: [], //币种
      channelCollectionIdOptions: [], //网管通道
      settleExchangeRateIdOptions: [],  // 结算汇率
      settleRateIdOptions: [], //交易费率
      riskIdOptions: [],   //分控
      mchTagIdOptions: [],
      salesIdOptions: [],
      apiStatusOptions: [{
        value: 0,
        label: "禁用"
      }, {
        value: 1,
        label: "正常"
      }],
      regStatusOptions: [{
        value: 0,
        label: "待审"
      }, {
        value: 1,
        label: "通过"
      }, {
        value: 2,
        label: "驳回"
      }, {
        value: 3,
        label: "禁用"
      }],
      loginStatusOptions: [{
        value: 0,
        label: "禁用"
      }, {
        value: 1,
        label: "正常"
      }],
      fromData: {
        mchId: this.id,
        mchName: "",
        channelCollection: [],
        settleRateId: "",
        settleExchangeRateId: "",
        riskId: "",
        salesId: "",
        mchTagId: [],
        regStatus: "",
        apiStatus: "",
        loginStatus: "",
        transCurrency: "",
        settleCurrency: "",
        CREDIT: "",
        DEBIT: "",
        ALIPAY: "",
        WECHAT_PAY: "",
      }

    }
  },

  methods: {
    submitChangeGoogleCode() {
      this.$confirm('确定重置google密钥？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        try {
          ApiMain.changeGoogleCode({ mchId: this.id }).then(() => {
            this.$message({ message: '重置google密钥成功！', type: 'success' });
          });
        } finally {

        }
      });
    },
    submitFormChangePassword() {
      this.$refs['form-change-password'].validate(valid => {
        if (this.formChangePassword.password_confirmation != this.formChangePassword.password) return this.$message({ message: '两次密码不一致!', type: 'warning' });
        if (valid) {
          this.formChangePassword.mchId = this.id
          ApiMain.changePassword(this.formChangePassword).then(() => {
            this.$message({ message: '密码修改成功', type: 'success' });

          });
        }
      });

    },
    async getConfig() {
      var _this = this
      this.channelCollectionIdOptions = await productApi.option()
      this.settleRateIdOptions = await rateSettleApi.option()
      this.settleExchangeRateIdOptions = await rateGroupApi.option()
      this.mchTagIdOptions = await mchTagApi.option()
      this.salesIdOptions = await memberApi.getOption({ extraType: 1, level: 2 })
      this.riskIdOptions = await collectionApi.option({ type: 2 })
      this.currencyOptions = await ApiRateBoc.getrateBocOptions({ page: 1, limit: 50 });
      console.log('币种', this.currencyOptions)
      //   这个时候再处理
    },
    handleCheckAllChange(val) {
      let arr = this.currencyOptions.map(item => {
        return item.value
      })
      this.checkedCities = val ? arr : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      console.log(value)
      console.log('??!@', this.cities)
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.currencyOptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.currencyOptions.length;
    },
    show(id = null) {

      this.id = id;

      if (this.id) {
        this.fetchData();
        this.getConfig()
      }

      this.dialogVisible = true;
    },

    close() {
      this.dialogVisible = false;
      this.$emit('dialog-close');
    },

    fetchData() {
      var _this = this
      try {
        ApiMain.getmchConfig({ mchId: this.id })
          .then(async re => {
            _this.payOptionList = await channelApi.payOption()
            _this.payOptionList.forEach(async (item, index) => {
              let option = await productApi.option({ payType: item.value })
              _this.$set(_this.payOptionList[index], 'option', option);
            })
            this.checkedCities = []
            console.log("选中的",)
            if (re.transCurrency) {
              this.checkedCities = re.transCurrency.split(',')

            }

            console.log(this.checkedCities, "????")
            re.channelCollection.forEach(item => {
              _this.payOptionList.forEach(ite => {
                if (ite.value == item.payType) {
                  re[ite.const] = item.id
                } else {
                  re[ite.const] = ''
                }
              })
            })



            this.fromData = re;
            //   这个时候再处理回显问题
          })
          .catch(() => {
            this.fromData = null;
            this.close()
          })
          .finally(() => {
            this.renderData();
          });
      } catch (error) {

      }


    },

    renderData() {
      console.log(this.data)
    },

    refresh() {
      this.fetchData();
      this.$message({ message: '已刷新', type: 'success' });
    },
    async submit() {

      this.$refs['main-form'].validate(valid => {
        if (valid) {


          let from = Object.assign({}, this.fromData)
          from.channelCollection = []
          this.payOptionList.forEach(item => {
            if (from[item.const]) {
              from.channelCollection.push({
                id: from[item.const],
                payType: item.value
              })
            }
            delete from[item.const]
          })

          if (from.channelCollection.length == 0) return this.$message({ message: '请至少选择一个通道合集！', type: 'warning' });
          if (this.checkedCities.length == 0) return this.$message({ message: '请至少选中一个币种！', type: 'warning' });
          from.transCurrency = ''
 
          this.checkedCities.forEach(item => {
            console.log(item)
            from.transCurrency += item + ','
          })
          from.transCurrency = from.transCurrency.substring(0, from.transCurrency.length - 1)

          ApiMain.setmchConfig(from).then(data => {
            this.$message({ message: '提交成功！', type: 'success' });
            this.close();
          })


        }
      });
    },
    copyData(ref, val) {
      this.$refs[ref].select()
      document.execCommand('copy');
      this.$message({ message: '已复制', type: 'success' });
    },
    submitStatus(channelId, status) {
      this.$confirm(status == 0 ? '确定操作关闭通道?此操作将会将该通道关闭，当日内不能产生交易' : '确定操作开启通道？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        try {
          ApiMain.setmchConfig({ terId: this.id, channelId: channelId, status: status });
        } finally {
          this.loading = false;
        }
        this.close();
        this.$message({ message: '操作成功', type: 'success' });
      });
    },

  }
}
</script>
<style lang="scss" scoped>
.dialog-footer {
  justify-content: space-between;
  display: flex;
  align-items: center;
}
</style>